package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"

	"github.com/spf13/cobra"
)

func init() {
	// sub.RegisterCommonFlags(tenantCmd)
	topicCmd.PersistentFlags().Int32VarP(&id, "id", "i", 0, "granary id")
	granaryCmd.AddCommand(topicCmd)
}

var topicCmd = &cobra.Command{
	Use:   "topic",
	Short: "Run list topic for a granary",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewGranaryServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		urn := utils.BuildUrn(utils.GranaryUrnPrefix, id)

		in := &v1pb.ListGranariesTopicsRequest{Urn: urn}
		rsp, err := qclient.ListGranariesTopics(ctxWithToken, in)
		if err != nil {
			return err
		}

		fmt.Println("seq         title")
		if rsp != nil {
			for index, v := range rsp.Topics {
				seq := index + 1
				fmt.Printf("%-5d %-20s \n", seq, v.Primary.Title)
				for j, u := range v.Units {
					s := fmt.Sprintf("%d-%d", seq, j+1)
					fmt.Printf("%-5s %-20s \n", s, u.Title)
				}
			}
		}
		// fmt.Print(rsp)
		return nil
	},
}
